package com.tro.generator.service.impl;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tro.common.util.file.FileUtils;
import com.tro.common.util.string.StringUtlis;
import com.tro.generator.entity.GenDicConfig;
import com.tro.generator.entity.GenDicConfigExample;
import com.tro.generator.entity.GenTable;
import com.tro.generator.entity.GenTableCol;
import com.tro.generator.entity.GenTableColExample;
import com.tro.generator.entity.GenTableColExt;
import com.tro.generator.entity.GenTableColExtExample;
import com.tro.generator.entity.GenTableColVO;
import com.tro.generator.entity.GenTableExample;
import com.tro.generator.ftl.FreeMarkerLoad;
import com.tro.generator.mapper.GenDicConfigMapper;
import com.tro.generator.mapper.GenTableColExtMapper;
import com.tro.generator.mapper.GenTableColMapper;
import com.tro.generator.mapper.GenTableMapper;
import com.tro.generator.service.GeneratorService;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

@Service
public class GeneratorServiceImpl implements GeneratorService {
	@Autowired
	GenTableMapper tableMapper;

	@Autowired
	GenTableColMapper colMapper;

	@Autowired
	GenTableColExtMapper colExtMapper;
	@Autowired
	GenDicConfigMapper dicMapper;

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Override
	public void refTables() {
		tableMapper.refTablesGenTable();
		tableMapper.updateTablesGenTable();
		tableMapper.refTablesGenTableCol();
	}

	@Override
	public void deleteGenTable(String id, String path) {
		GenTableColExample colExample = new GenTableColExample();
		colExample.createCriteria().andTableIdEqualTo(id);
		List<GenTableCol> col = colMapper.selectByExample(colExample);
		// 懒得写批量删除了
		GenDicConfigExample dicExample = new GenDicConfigExample();
		GenTableColExtExample extExample = new GenTableColExtExample();
		for (GenTableCol c : col) {

			extExample = new GenTableColExtExample();
			extExample.createCriteria().andColIdEqualTo(c.getId());
			dicExample = new GenDicConfigExample();
			dicExample.createCriteria().andColIdEqualTo(c.getId());
			colExtMapper.deleteByExample(extExample);
			dicMapper.deleteByExample(dicExample);
		}

		colMapper.deleteByExample(colExample);// 删除
		tableMapper.deleteByPrimaryKey(id);
		// 文件删除
		FileUtils.deleteFile(path + "/" + id + "_list.jsp");
		FileUtils.deleteFile(path + "/" + id + "form_jsp");

	}

	@Override
	public List<GenTable> selectByExampleGenTable(GenTableExample example) {
		// TODO Auto-generated method stub
		return tableMapper.selectByExample(example);
	}

	@Override
	public List<GenTableCol> selectByExampleGenTableCol(GenTableColExample example) {
		// TODO Auto-generated method stub
		return colMapper.selectByExample(example);
	}

	@Override
	public GenTable selectByPrimaryKey(String id) {
		// TODO Auto-generated method stub
		return tableMapper.selectByPrimaryKey(id);
	}

	@Override
	@Transactional
	public void generatorSource(GenTable genTable, List<GenTableCol> col, List<GenDicConfig> dics,
			List<GenTableColExt> extCols, String savePath) throws TemplateException, IOException {
		// 更新数据表
		tableMapper.updateByPrimaryKeySelective(genTable);
		GenTableColExample colExample = new GenTableColExample();
		colExample.createCriteria().andTableIdEqualTo(genTable.getId());
		colMapper.deleteByExample(colExample);// 先删除
		colMapper.insertBatch(col);
		// 懒得写批量删除了
		GenDicConfigExample dicExample = new GenDicConfigExample();
		GenTableColExtExample extExample = new GenTableColExtExample();
		for (GenTableCol c : col) {

			extExample = new GenTableColExtExample();
			extExample.createCriteria().andColIdEqualTo(c.getId());
			dicExample = new GenDicConfigExample();
			dicExample.createCriteria().andColIdEqualTo(c.getId());
			colExtMapper.deleteByExample(extExample);
			dicMapper.deleteByExample(dicExample);
		}
		// 懒得写批量插入。。😶
		for (GenDicConfig d : dics) {
			d.setId(StringUtlis.getGUID());
			dicMapper.insert(d);
		}
		for (GenTableColExt d : extCols) {
			d.setId(StringUtlis.getGUID());
			colExtMapper.insert(d);
		}
		List<GenTableColVO> listColVOs = buildGenTableColVO(col, dics, extCols);
		if (genTable.getGtableStyle().equals("1")) {
			Map<String, Object> product = new HashMap<>();
			product.put("cols", listColVOs);
			product.put("genTable", genTable);
			FreeMarkerLoad.BuildFreeMarker(product, savePath, genTable.getId() + "_list.jsp", "easyui-list.ftl");
			FreeMarkerLoad.BuildFreeMarker(product, savePath, genTable.getId() + "_form.jsp", "easyui-form.ftl");
		}

	}

	List<GenTableColVO> buildGenTableColVO(List<GenTableCol> col, List<GenDicConfig> dics,
			List<GenTableColExt> extCols) {
		List<GenTableColVO> result = new ArrayList<>();
		GenTableColVO vo = new GenTableColVO();
		if (col == null || col.size() == 0) {
			return result;
		}
		for (int i = 0; i < col.size(); i++) {
			vo = new GenTableColVO();
			vo.setId(col.get(i).getId());
			vo.setTableId(col.get(i).getTableId());
			vo.setColName(col.get(i).getColName());
			vo.setColComment(col.get(i).getColComment());
			vo.setFormShow(col.get(i).getFormShow());
			vo.setListShow(col.get(i).getListShow());
			vo.setInputType(col.get(i).getInputType());
			vo.setIsSearch(col.get(i).getIsSearch());
			vo.setSearchType(col.get(i).getSearchType());
			vo.setValidateRules(col.get(i).getValidateRules());
			vo.setDataType(col.get(i).getDataType());
			vo.setDataLength(col.get(i).getDataLength());
			vo.setSortNum(col.get(i).getSortNum());
			vo.setColWidth(extCols.get(i).getColWidth());
			vo.setColHeight(extCols.get(i).getColHeight());
			vo.setDefaultVal(extCols.get(i).getDefaultVal());
			vo.setIsEditor(extCols.get(i).getIsEditor());
			vo.setGroupName(extCols.get(i).getGroupName());
			vo.setExtId(extCols.get(i).getId());
			vo.setDicId(dics.get(i).getId());
			vo.setDicTable(dics.get(i).getDicTable());
			vo.setDicTableKey(dics.get(i).getDicTableKey());
			vo.setDicTableText(dics.get(i).getDicTableText());
			vo.setDicJson(dics.get(i).getDicJson());
			vo.setColFormat(dics.get(i).getColFormat());
			result.add(vo);
		}
		return result;
	}

	void buildEasyUIForm(GenTable genTable, List<GenTableCol> col, String savePath)
			throws TemplateException, IOException {
		// 指定版本号
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
		// 设置模板目录
		// cfg.setDirectoryForTemplateLoading(new
		// File("classpath*:/com/tro/generator/ftl"));
		cfg.setClassForTemplateLoading(FreeMarkerLoad.class, "");
		// 设置默认编码格式
		cfg.setDefaultEncoding("UTF-8");

		Map<String, Object> product = new HashMap<>();
		product.put("cols", col);
		product.put("genTable", genTable);

		// 从设置的目录中获得模板
		Template temp = cfg.getTemplate("easyui-form.ftl");
		Writer out = new FileWriter(new File(savePath + "/" + genTable.getGtableName() + "_form.jsp"));
		temp.process(product, out);
		// 关闭
		out.flush();
		out.close();
	}

	@Override
	public int countByExampleGenTable(GenTableExample example) {
		// TODO Auto-generated method stub
		return tableMapper.countByExample(example);
	}

	@Override
	public void insertSql(String sql) {
		// TODO Auto-generated method stub
		tableMapper.insertSql(sql);
	}

	@Override
	public List<Map<String, Object>> querySql(String sql) {
		// TODO Auto-generated method stub
		return tableMapper.querySql(sql);
	}

	@Override
	public void delSql(String sql) {
		// TODO Auto-generated method stub
		tableMapper.delSql(sql);
	}

	@Override
	public void updateSql(String sql) {
		// TODO Auto-generated method stub
		tableMapper.updateSql(sql);
	}

	@Override
	public Integer countSql(String sql) {
		// TODO Auto-generated method stub
		return tableMapper.countSql(sql);
	}

	/**
	 * 
	 * @Title: init
	 * @Description: TODO(spring 容器启动后执行初始化操作)
	 * @param 设定文件
	 * @return void 返回类型
	 * @throws @author
	 *             leeko
	 */
	@PostConstruct
	public void init() {
		logger.info("检查数据表是否存在..........");

	}

	@Override
	public List<GenTableColVO> getCols(String tableId) {
		return tableMapper.getCols(tableId);
	}

	@Override
	public GenTableCol selectByPrimaryKeyCol(String id) {
		return colMapper.selectByPrimaryKey(id);
	}

	@Override
	public GenDicConfig selectByKeyDic(String id) {

		return dicMapper.selectByPrimaryKey(id);
	}

	@Override
	@Transactional
	public void copyGenTable(String id) {
		
		GenDicConfigExample dicExample = new GenDicConfigExample();
		GenTableColExtExample extExample = new GenTableColExtExample();
		
		GenTable table = tableMapper.selectByPrimaryKey(id);
		String tableId = StringUtlis.getGUID();
		table.setId(tableId);
		table.setUpdateTime(new Date());

		GenTableColExample colExample = new GenTableColExample();
		colExample.createCriteria().andTableIdEqualTo(id);
		List<GenTableCol> cols = colMapper.selectByExample(colExample);
		for (GenTableCol c : cols) {
			String colId = StringUtlis.getGUID();
			extExample = new GenTableColExtExample();
			extExample.createCriteria().andColIdEqualTo(c.getId());
			dicExample = new GenDicConfigExample();
			dicExample.createCriteria().andColIdEqualTo(c.getId());
			List<GenTableColExt> colExts = colExtMapper.selectByExample(extExample);
			List<GenDicConfig> dics = dicMapper.selectByExample(dicExample);
			for (GenTableColExt e : colExts) {
				e.setId(StringUtlis.getGUID());
				e.setColId(colId);
				colExtMapper.insert(e);
			}
			for (GenDicConfig e : dics) {
				e.setId(StringUtlis.getGUID());
				e.setColId(colId);
				dicMapper.insert(e);
			}
			c.setId(colId);
			c.setTableId(tableId);
			colMapper.insert(c);
		}
		tableMapper.insert(table);
	}
}
